#include "websockserver.h"
//#include "chat_server.h"
#include "c_session_webs.h"
broadcast_server _hserver;


void registerhttp()
{
	broadcast_server& _httpserver = _hserver;
	_httpserver.func_proc_register("/login", [](maps_pair& rp) {

		auto iter = rp.begin();
		while (iter != rp.end())
		{
			std::cout << iter->first << " " << iter->second << std::endl;
		}
		return;
		});

	_httpserver.func_proc_register("/url", [](maps_pair& rp) {
		cout << "url get" << endl;
		return;
		});

}
//
//int main(int argc, char** argv)
//{
//	registerhttp();
//	_hserver.Start(3000);
//	_hserver.Join();
//	return 0;
//}


static void callback(en_data_type type, uint8_t* mem, uint8_t* data, size_t len)
{
#define D(x) data[x]
	if (type == 0x01)//text
	{
		std::string s((char*)data, len);
		std::cout << s << std::endl;
	}
	else
	{
		printf("%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x---len is %zd\n",
			D(0),
			D(1),
			D(2), D(3), D(4), D(5), D(6), D(7), D(8), D(9), D(10)
			, len);
	}
}

static void callback_http(c_header_map* map, uint8_t* data, size_t len)
{

	auto iter = map->begin();
	while (iter != map->end())
	{
		cout << iter->first << " ->" <<iter->second << endl;
		iter++;
	}
}

//typedef shared_ptr<c_session_webs> ptr_webs;
awaitable<void> listener(tcp::acceptor acceptor)
{
	//chat_room room;

	for (;;)
	{
		//tcp::socket so = co_await acceptor.async_accept(use_awaitable);
		//ptr_webs ptrweb = std::make_shared<c_session_webs>(so);
		//ptrweb->func_setcb(callback, callback_http);
		std::make_shared<c_session_webs>(
			co_await acceptor.async_accept(use_awaitable)
			)->start(callback, callback_http);
	}
}

int main(int argc, char* argv[])
{
	uint16_t port = 6001;
	try
	{
		if (argc == 2)
		{
			port = std::atoi(argv[1]);
		}

		asio::io_context io_context(1);

		co_spawn(io_context,
			listener(tcp::acceptor(io_context, { tcp::v4(), port })),
			detached);


		asio::signal_set signals(io_context, SIGINT, SIGTERM);
		signals.async_wait([&](auto, auto) { io_context.stop(); });
		cout << "websocket server run at " << port << endl;
		io_context.run();
	}
	catch (std::exception& e)
	{
		std::cerr << "Exception: " << e.what() << "\n";
	}

	return 0;
}
